using System;
using System.Collections.Generic;
using System.Reflection;

namespace WebBridge
{
    class FxProxy
    {
        private readonly object _instance;
        private readonly IDictionary<string, MethodInfo> _methods;

        public FxProxy(Type type, Object instance)
        {
            Name = type.Name;
            _instance = instance;
            _methods = new Dictionary<string, MethodInfo>();

            var methods = type.GetMethods();
            foreach (var mi in methods)
            {
                _methods.Add(mi.Name, mi);
            }
        }

        public string Name { get; private set; }

        public void Invoke(FxArgs args)
        {
            var method = _methods[args.Method];
            object ret;

            try
            {
                ret = method.Invoke(_instance, args.Arguments);
            }
            catch (Exception e)
            {
                // TODO:
                throw e.InnerException;
            }

            if (method.ReturnType != typeof(void))
            {
                var bin = FxArgs.Serialize(ret);
                if (bin.Length > args.ReturnLength)
                {
                    throw new InsufficientMemoryException("Allocate bigger memory address first");
                }
                // TODO
                // memcpy(bin, args.ReturnPtr, bin.Length);
            }
        }
    }
}